<!-- 添加推广链接 -->
<!-- 添加推广链接 -->
<template>
  <el-dialog
      v-model="dialogVisible"
      width="80%"
      :title="action === 'edit' ? '编辑推广链接' : action === 'add' ? '添加推广链接' : '推广链接详情'"
      draggable
      appendToBody
      destroyOnClose
      lockScroll
      :closeOnClickModal="false"
  >
    <base-skeleton v-if="pageLoad.loadState === true" style="width: 100%; height: 100%; min-height: 420px; padding: 0 20px"></base-skeleton>
    <template v-else-if="pageLoad.loadState === false">
      <el-form ref="elFormRef" :validateOnRuleChange="false" :model="formData" :rules="rules" scrollToError :disabled="disabled">
        <div style="display: flex; gap: 20px">
          <div v-auto-animate style="flex: 1">
            <el-form-item label="链接名称" labelWidth="8em" prop="referralLinkName">
              <el-input v-model="formData.referralLinkName" :maxlength="80" clearable placeholder="请输入链接名称"></el-input>
            </el-form-item>
            <el-form-item label="投广渠道" labelWidth="8em" prop="channel">
              <box-from-border :disabled="disabled">
                <el-radio-group v-model="formData.channel" @change="channelChangeHandler">
                  <el-radio v-for="item in channelList" :key="item.value" :label="item.label" :value="item.value"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <el-form-item v-if="formData.channel" label="投广平台" labelWidth="8em" prop="platform">
              <box-from-border :disabled="disabled">
                <el-radio-group v-model="formData.platform" @change="platformListChangeHandler">
                  <el-radio v-for="item in platformList" :key="item.value" :label="item.label" :value="item.value"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <el-form-item v-if="formData.platform" key="el-form-item-1" label="推广模式" labelWidth="8em" prop="iaaFlag">
              <box-from-border :disabled="disabled">
                <el-radio-group v-model="formData.iaaFlag" @change="iaaFlagChangeHandler">
                  <el-radio label="付费(IAP)" :value="0"></el-radio>
                  <el-radio label="免费(IAA)" :value="1"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <el-form-item v-if="formData.platform" key="el-form-item-2" label="小程序" labelWidth="8em" prop="investmentId">
              <box-from-border :disabled="disabled">
                <el-radio-group v-model="formData.investmentId">
                  <el-radio v-for="item in mpList" :key="item.investmentId" :label="item.label" :value="item.investmentId"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <el-form-item label="选择短剧" labelWidth="8em" prop="drama">
              <bubble-select-local
                  v-model="formData.drama"
                  labelKey="dramaTitle"
                  valueKey="dramaId"
                  returnOriginal
                  :axios="getDramaListAxios"
                  placeholder="请选择短剧"
                  @change="dramaChangeHandler"
              ></bubble-select-local>
            </el-form-item>
            <el-form-item v-if="formData.drama" key="el-form-item-3" label="选择剧集" labelWidth="8em" prop="episode">
              <bubble-select-local
                  v-model="formData.episode"
                  :list="episodeList"
                  labelKey="episodeTitle"
                  valueKey="episodeId"
                  returnOriginal
                  disabled
                  :automaticDropdown="false"
                  placeholder="请选择剧集"
              >
                <template #default="{ item }">
                  <el-option :label="item.episodeTitle" :value="item.episodeId"></el-option>
                </template>
              </bubble-select-local>
            </el-form-item>
            <el-form-item label="单集解锁价格" labelWidth="8em" prop="price">
              <base-input-number v-model="formData.price" :max="100000" verify="add_int" placeholder="请输入单集解锁价格" clearable>
                <template #suffix>K币</template>
              </base-input-number>
            </el-form-item>
            <el-form-item label="起始付费集数" labelWidth="8em" prop="rechargeEpisodeNum">
              <base-input-number
                  v-model="formData.rechargeEpisodeNum"
                  verify="add_int_or_zero"
                  placeholder="请输入从第几集开始付费(包含该集)"
                  clearable
              ></base-input-number>
            </el-form-item>
            <el-form-item labelWidth="8em" label="商品模板" prop="productTemplateId" @click="handleSelectTemplate(4)">
              <box-from-border isClick placeholder="请选择商品模版" :disabled="disabled" :text="formData.dramaFirstTemplate.templateName"></box-from-border>
            </el-form-item>
            <el-form-item
                v-if="formData.productTemplateId && formData.iaaFlag === 0"
                key="el-form-item-5"
                label="IAP回传模板"
                labelWidth="8em"
                prop="productBackTemplateId"
            >
              <bubble-select-local
                  v-model="iapBackTemplate"
                  :disabled="!formData.productTemplateId"
                  :axios="getAllBackTemplateListAxios"
                  :param="{ productTemplateId: formData.productTemplateId }"
                  labelKey="backTemplateName"
                  valueKey="productBackTemplateId"
                  returnOriginal
                  :automaticDropdown="false"
                  placeholder="请选择IAP回传模版"
              ></bubble-select-local>
            </el-form-item>
            <el-form-item v-if="formData.iaaFlag === 1" key="el-form-item-5" label="IAA回传模板" labelWidth="8em" prop="productBackTemplateId">
              <bubble-select-local
                  v-model="iaaBackTemplate"
                  :axios="getIAAAllBackTemplateListAxios"
                  labelKey="iaaRuleName"
                  valueKey="iaaBackTemplateId"
                  returnOriginal
                  :automaticDropdown="false"
                  placeholder="请选择IAA回传模版"
              ></bubble-select-local>
            </el-form-item>
            <el-form-item v-if="formData.channel == 'baidu'" key="el-form-item-5" label="百度token" labelWidth="8em" prop="baiduToken">
              <el-input v-model="formData.baiduToken" :maxlength="80" clearable placeholder="请输入baiduToken"></el-input>
            </el-form-item>
            <el-form-item v-if="formData.iaaFlag === 0" key="el-form-item-5" label="广告解锁" labelWidth="8em" prop="advertUnlock">
              <box-from-border :disabled="disabled">
                <el-radio-group v-model="formData.advertUnlock">
                  <el-radio label="不支持" :value="0"></el-radio>
                  <el-radio label="支持" :value="1"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <el-form-item label="备注" labelWidth="8em" prop="remark">
              <el-input v-model="formData.remark" :maxlength="12" clearable placeholder="请输入备注"></el-input>
            </el-form-item>
          </div>
          <div style="flex: 1; overflow: hidden">
            <div class="content-vessel">
              <div class="content-box" @click="handleSelectTemplate(4)">
                <page-simulation-template
                    :selectIndex="formData.dramaFirstTemplate.selectIndex"
                    :templateProductList="formData.dramaFirstTemplate.productList"
                ></page-simulation-template>
                <div class="title-box">
                  <el-button style="width: 100%" :icon="IconPointer" type="primary">
                    {{ formData.productTemplateId ? '重选商品模版' : '选择商品模版' }}
                  </el-button>
                </div>
              </div>
            </div>
            <el-divider contentPosition="center">剩余K币</el-divider>
            <el-table border :data="virtualCurrencyBalanceCpt" showOverflowTooltip stripe style="width: 100%">
              <template #empty>
                <span>{{ formData.productTemplateId ? '暂无数据' : '选择商品模板后查看' }}</span>
              </template>
              <el-table-column label="挡位" prop="productPrice" :formatter="(row) => `${row.productPrice}元`"></el-table-column>
              <el-table-column label="K币数量" prop="productQuantity"></el-table-column>
              <el-table-column label="可看至" prop="numberOfEpisodes" :formatter="(row) => `${row.numberOfEpisodes}集`"></el-table-column>
              <el-table-column label="剩余K币" prop="balance"></el-table-column>
            </el-table>
          </div>
        </div>
        <el-form-item v-if="!disabled" key="el-form-item-4" labelWidth="0em">
          <div style="width: 100%; padding-top: 20px">
            <el-button style="width: 100%" type="success" :disabled="loading" :loading="loading" @click="submit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <base-empty
        v-else
        style="height: 100%"
        :description="pageLoad.description || ''"
        :imageSize="240"
        :loadState="pageLoad.loadState"
        :pageLoadButton="[{ text: '重新加载', callBack: getBaseDataAxios }]"
    ></base-empty>
    <page-select-template ref="pageSelectTemplateRef"></page-select-template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { vAutoAnimate } from '@formkit/auto-animate/vue';
import IconPointer from '~icons/ep/pointer';
import {
  type BaseBackTemplate,
  type Drama,
  type Episode,
  type IaaBaseBackTemplate,
  type MpInfo,
  type ReferralLink,
  type ReferralRecord,
  type ReferralTemplate,
  type TemplateProductMarketingInfo,
  addReferralRecordAxios,
  editReferralRecordAxios,
  getAllBackTemplateListAxios,
  getDramaListAxios,
  getEpisodeListAxios,
  getIAAAllBackTemplateListAxios,
  getMpInfoAxios,
  getTemplateInfoByReferralLinkId,
} from '@/api/marketing-management';
import { filterRepeat } from '@/utils/data';
import PageSelectTemplate from '@/components/page/page-select-template/page-select-template.vue';

type $EditShowData = {
  /** 操作 */
  action: 'clone' | 'edit';
  referralRecord: ReferralRecord;
  /** 审核后的回调 */
  editCallBack?: () => void;
};

type $AddShowData = {
  /** 操作 */
  action: 'add';
  /** 审核后的回调 */
  addCallBack?: () => void;
};

type $DetailsShowData = {
  /** 操作 */
  action: 'details';
  referralRecord: ReferralRecord;
};

type SelectType = { label: string; value: string };

type $ShowData = $AddShowData | $DetailsShowData | $EditShowData;
type FormData = Omit<ReferralLink, 'dramaId' | 'episodeId' | 'productBackTemplateId'> & {
  /** 短剧信息 */
  drama: Drama | undefined;
  /** 剧集信息 */
  episode: Episode | undefined;
  /** 渠道列表 */
  channel: MpInfo['investmentChannel'] | '';
  /** 平台列表 */
  platform: MpInfo['platformType'] | '';
  /** 小程序 */
  appid: MpInfo['appId'] | '';
  /** 投广渠道-平台关联id */
  investmentId: MpInfo['investmentId'] | '';
  dramaFirstTemplate: TemplateProductMarketingInfo;
};

const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });

let addCallBack: $AddShowData['addCallBack'] = undefined;
let editCallBack: $EditShowData['editCallBack'] = undefined;

const dialogVisible = ref(false);
const elFormRef: Ref<FormInstance | null> = ref(null);
const pageSelectTemplateRef: Ref<InstanceType<typeof PageSelectTemplate> | null> = ref(null);
const action = ref<'add' | 'clone' | 'details' | 'edit'>();
const loading = ref(false);
const mpInfoLIst = shallowRef<MpInfo[]>([]);
const episodeList = ref<Episode[]>([]);

const disabled = computed(() => action.value === 'details');

const formData = reactive<FormData>({
  referralLinkName: '',
  drama: undefined,
  episode: undefined,
  pushPlatform: 1,
  referralLinkId: null,
  remark: '',
  channel: 'juliang',
  platform: 'mp-weixin',
  iaaFlag: 0,
  appid: '',
  appCode: '',
  investmentId: undefined,
  price: null,
  rechargeEpisodeNum: null,
  productTemplateId: undefined,
  advertUnlock: 0,
  dramaFirstTemplate: {
    templateName: '',
    templateType: 4,
    selectIndex: 0,
    advertUnlock: 0,
    productList: [],
  },
});
/** IAP回传模版信息 */
const iapBackTemplate = ref<BaseBackTemplate | undefined>(undefined);
/** IAA回传模版信息 */
const iaaBackTemplate = ref<IaaBaseBackTemplate | undefined>(undefined);

/** 渠道列表 */
const channelList = computed(() => {
  const list = filterRepeat(mpInfoLIst.value, 'investmentChannel').map((item) => ({
    label: item.investmentChannelName,
    value: item.investmentChannel,
  }));

  return list;
});

/** 平台列表 */
const platformList = computed<SelectType[]>(() => {
  if (formData.channel) {
    const list: SelectType[] = [];
    mpInfoLIst.value.forEach((item) => {
      if (formData.channel === item.investmentChannel) {
        list.push({ label: item.platformName, value: item.platformType });
      }
    });
    return filterRepeat(list, 'value');
  } else {
    return [];
  }
});

/** 小程序列表 */
const mpList = computed(() => {
  if (formData.channel && formData.platform) {
    const list: { label: string; value: string; investmentId: number; iaaFlag: 0 | 1 }[] = [];
    mpInfoLIst.value.forEach((item) => {
      if (formData.channel === item.investmentChannel && formData.platform === item.platformType && item.iaaFlag === formData.iaaFlag) {
        list.push({ label: item.appName, value: item.appId, investmentId: item.investmentId!, iaaFlag: item.iaaFlag });
      }
    });
    return filterRepeat(list, 'value');
  } else {
    return [];
  }
});

const rules = computed(() => {
  const _rules: FormRules<FormData> = {
    referralLinkName: [{ required: true, type: 'string', message: '请输入链接名称', trigger: ['blur', 'change'] }],
    channel: [{ required: true, type: 'string', message: '请选择投广渠道', trigger: ['blur', 'change'] }],
    platform: [{ required: true, type: 'string', message: '请选择投广平台', trigger: ['blur', 'change'] }],
    investmentId: [{ required: true, type: 'number', message: '请选择小程序', trigger: ['blur', 'change'] }],
    drama: [{ required: true, type: 'object', message: '请选择短剧', trigger: ['blur', 'change'] }],
    episode: [{ required: true, type: 'object', message: '请选择剧集', trigger: ['blur', 'change'] }],
    pushPlatform: [
      { required: true, type: 'number', message: '请选择平台', trigger: ['blur', 'change'] },
      { type: 'enum', enum: [1, 2], message: `平台不合法`, trigger: ['blur', 'change'] },
    ],
    productTemplateId: [{ required: true, message: '请选择商品模板', trigger: ['blur', 'change'] }],
    advertUnlock: [{ required: true, message: '广告解锁', trigger: ['blur', 'change'] }],
  };
  return _rules;
});

/**
 * 提交
 */
async function submit() {
  try {
    await elFormRef.value?.validate();
    try {
      loading.value = true;
      selectChannelAndPlatform();
      const data: ReferralLink = {
        referralLinkName: formData.referralLinkName || '',
        dramaId: formData.drama?.dramaId || null,
        episodeId: formData.episode?.episodeId || null,
        pushPlatform: formData.pushPlatform ?? 1,
        referralLinkId: action.value === 'edit' ? formData.referralLinkId : null,
        price: formData.price || null,
        investmentId: formData.investmentId,
        rechargeEpisodeNum: formData.rechargeEpisodeNum || null,
        remark: formData.remark || '',
        productTemplateId: formData.productTemplateId,
        productBackTemplateId: iapBackTemplate.value?.productBackTemplateId || null,
        iaaBackTemplateId: iaaBackTemplate.value?.iaaBackTemplateId || null,
        advertUnlock: formData.advertUnlock,
        iaaFlag: formData.iaaFlag,
        appCode: formData.appCode,
        baiduToken: formData.baiduToken,
      };

      if (action.value === 'edit') {
        await editReferralRecordAxios(data);
        typeof editCallBack === 'function' && editCallBack();
      } else {
        await addReferralRecordAxios(data);
        typeof addCallBack === 'function' && addCallBack();
      }
      loading.value = false;
      ElToast.success('添加成功');
      hide();
    } catch (error) {
      console.log('aaa====', error);
      loading.value = false;
      ElToast.error(error.msg || '提交失败，-BD001');
    }
  } catch (error) {
    ElToast.error('提交失败，请完善表单，-BD002');
  }
}

const initFormData = () => {
  iapBackTemplate.value = undefined;
  iaaBackTemplate.value = undefined;
  formData.referralLinkName = '';
  formData.drama = undefined;
  formData.channel = 'juliang';
  formData.platform = 'mp-weixin';
  formData.iaaFlag = 0;
  formData.appCode = '';
  formData.investmentId = undefined;
  formData.episode = undefined;
  formData.pushPlatform = 1;
  formData.referralLinkId = null;
  formData.price = null;
  formData.rechargeEpisodeNum = null;
  formData.remark = '';
  formData.productTemplateId = undefined;
  formData.advertUnlock = 0;
  formData.dramaFirstTemplate = {
    templateName: '',
    templateType: 4,
    selectIndex: 0,
    advertUnlock: 0,
    productList: [],
  };
};

/**
 * 显示
 */
function show(data: $ShowData) {
  action.value = data.action;
  initFormData();
  if (data.action === 'edit' || data.action === 'clone' || data.action === 'details') {
    formData.referralLinkName = data.referralRecord.referralLinkName || '';
    formData.pushPlatform = data.referralRecord.pushPlatform ?? 1;
    formData.referralLinkId = data.referralRecord.referralLinkId;
    formData.price = data.referralRecord.price;
    formData.rechargeEpisodeNum = data.referralRecord.rechargeEpisodeNum;
    formData.investmentId = data.referralRecord.investmentId || undefined;
    formData.remark = data.referralRecord.remark || '';
    formData.drama = undefined;
    formData.episode = undefined;
    formData.productTemplateId = data.referralRecord.productTemplateId || undefined;
    formData.advertUnlock = data.referralRecord.advertUnlock || 0;
    if (data.referralRecord.dramaId && data.referralRecord.dramaTitle) {
      formData.drama = { dramaId: data.referralRecord.dramaId, dramaTitle: data.referralRecord.dramaTitle };
    }
    if (data.referralRecord.episodeId) {
      formData.episode = { episodeId: data.referralRecord.episodeId, episodeTitle: `第${(data.referralRecord.episodeSeq || 0) + 1}集` };
    }
  }

  addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
  editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;

  dialogVisible.value = true;

  getBaseDataAxios();
}

/**
 * 隐藏
 */
function hide() {
  dialogVisible.value = false;
}

/** 请求 */
async function getBaseDataAxios() {
  try {
    pageLoad.loadState = true;

    const res = await Promise.all(
        formData.referralLinkId ? [getMpInfoAxios(), getTemplateInfoByReferralLinkId(formData.referralLinkId)] : [getMpInfoAxios()]
    );

    console.log(res, 'rrrrrrrrrr');

    mpInfoLIst.value = res[0].data || [];
    if (res[1]) {
      iapBackTemplate.value = res[1].data.productTemplateId
          ? { productBackTemplateId: res[1].data.productBackTemplateId, backTemplateName: res[1].data.backTemplateName || '' }
          : undefined;
      iaaBackTemplate.value = res[1].data.iaaBackTemplateId
          ? { iaaBackTemplateId: res[1].data.iaaBackTemplateId, iaaRuleName: res[1].data.iaaRuleName || '' }
          : undefined;
      formData.dramaFirstTemplate = {
        ...res[1].data,
        productList: res[1].data.productList || [],
        templateName: res[1].data.templateName || '',
        templateType: res[1].data.templateType || 4,
        selectIndex: res[1].data.selectIndex || 0,
        advertUnlock: res[1].data.advertUnlock || 0,

      };
    }
    if(res[1] && res[1].data && res[1].data.baiduToken){
      formData.baiduToken= res[1].data.baiduToken ||''
    }

    const mpInfo = mpInfoLIst.value.find((item) => item.investmentId === formData.investmentId);
    formData.iaaFlag = mpInfo?.iaaFlag || 0;

    pageLoad.loadState = false;
    if (action.value === 'edit' || action.value === 'clone' || action.value === 'details') {
      selectChannelAndPlatform();
    }
  } catch (error) {
    pageLoad.loadState = 'err';
    pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
  }
}

/** 编辑回显渠道和平台 */
function selectChannelAndPlatform() {
  if (formData.investmentId) {
    const mpInfo = mpInfoLIst.value.find((item) => item.investmentId === formData.investmentId);
    if (mpInfo) {
      formData.channel = mpInfo.investmentChannel;
      formData.iaaFlag = mpInfo.iaaFlag;
      formData.platform = mpInfo.platformType;
      formData.appCode = mpInfo.appCode;
    }
  }
}

/** 短剧变更填充默认剧集 */
async function dramaChangeHandler(val: Drama) {
  try {
    formData.episode = undefined;
    const { data } = await getEpisodeListAxios({ dramaId: val.dramaId });
    episodeList.value = data ?? [];
    if (data.length) {
      formData.episode = data[0];
    }
  } catch (error) {}
}

/** 渠道变更重置平台 */
function channelChangeHandler() {
  formData.platform = '';
  formData.investmentId = undefined;

}

/** 平台变更重置小程序 */
function platformListChangeHandler() {
  formData.investmentId = undefined;
}
/** 是否为iaa变更充值小程序 */
function iaaFlagChangeHandler() {
  formData.investmentId = undefined;
}

const virtualCurrencyBalanceCpt = computed(() => {
  const virtualCurrencyList = formData.dramaFirstTemplate.productList.filter((item) => item.productType === 1);
  for (const item of virtualCurrencyList) {
    if (item.productQuantity && formData.price) {
      if (Number(formData.price) > Number(item.productQuantity)) {
        item.numberOfEpisodes = 0;
        item.balance = item.productQuantity;
      } else {
        item.numberOfEpisodes = Math.floor(Number(item.productQuantity) / Number(formData.price)) + (Number(formData.rechargeEpisodeNum) || 0);
        item.balance = Number(item.productQuantity) % Number(formData.price);
      }
    } else {
      item.numberOfEpisodes = '';
      item.balance = '';
    }
  }
  return virtualCurrencyList;
});

/**
 * 选择模板
 */
function handleSelectTemplate(templateType: 1 | 2 | 4) {
  if (!disabled.value) {
    pageSelectTemplateRef.value?.show({
      templateType,
      selectCallBack(res: ReferralTemplate) {
        if (formData.productTemplateId !== res.productTemplateId) {

          console.log(res,"====res")

          formData.dramaFirstTemplate = res;
          formData.productTemplateId = res.productTemplateId!;
          formData.advertUnlock = res.advertUnlock;
          iapBackTemplate.value = undefined;
        }
      },
    });
  }
}

defineExpose({ show, hide });
</script>

<style scoped lang="scss">
.content-vessel {
  display: grid;
  grid-template-columns: repeat(auto-fill, 259px);
  gap: 15px;
  width: 100%;

  .content-box {
    overflow: hidden;
    cursor: pointer;
    background: $c-bg-block;
    border-radius: 10px;
    box-shadow: var(--my-box-shadow-fill);

    .title-box {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      padding: 10px;
    }
  }
}
</style>
